package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysExtenFieldsValue;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.copy.LabChannelCopy;
import com.ysd.lis.entity.copy.LabItemDictCopy;
import com.ysd.lis.entity.copy.LabItemDictCriticalCopy;
import com.ysd.lis.entity.copy.LabItemDictReferCopy;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.entity.qi.QiIndexFeeitemManual;
import com.ysd.lis.entity.sta.StaFeeItem;
import com.ysd.lis.entity.sta.StaFeeitemVsItemdict;
import com.ysd.lis.entity.sta.StaItemDict;
import com.ysd.lis.entity.synItemData.KnowBase;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.qi.QiIndexFeeitemManualMapper;
import com.ysd.lis.mapper.sta.StaItemDictMapper;
import com.ysd.lis.mapper.sys.SysExtenFieldsMapper;
import com.ysd.lis.mapper.sys.SysExtenFieldsValueMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.ExtenFieldsValuePageRequestDto;
import com.ysd.lis.request.StaDictItemSyncDto;
import com.ysd.lis.request.lab.FindItemDictKnoInfoParam;
import com.ysd.lis.request.lab.LabItemDictDto;
import com.ysd.lis.request.qc.QcInstrSampleParam;
import com.ysd.lis.service.SysExtenFieldsValueService;
import com.ysd.lis.service.lab.LabChannelService;
import com.ysd.lis.service.lab.LabItemDictCriticalService;
import com.ysd.lis.service.lab.LabItemDictReferService;
import com.ysd.lis.service.lab.LabItemDictService;
import com.ysd.lis.util.EasyExcelExport;
import com.ysd.lis.util.EasyExcelSheet;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yangjianguang
 * @since 2023-12-11
 */
@Service
public class LabItemDictServiceImpl extends ServiceImpl<LabItemDictMapper, LabItemDict> implements LabItemDictService {

    @Autowired
    private LabItemDictMapper labReportItemMapper;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabChannelMapper labChannelMapper;

    @Autowired
    LabInstrSetupMapper labInstrSetupMapper;

    @Autowired
    LabRptGroupMapper labRptGroupMapper;

    @Autowired
    QiIndexFeeitemManualMapper qiIndexFeeitemManualMapper;

    @Autowired
    SysExtenFieldsMapper sysExtenFieldsMapper;

    @Autowired
    SysExtenFieldsValueMapper sysExtenFieldsValueMapper;

    @Autowired
    SysExtenFieldsValueService sysExtenFieldsValueService;

    @Autowired
    StaItemDictMapper staItemDictMapper;
    
    @Autowired
    LabItemDictReferMapper itemDictReferMapper;
    @Autowired
    LabItemDictReferService itemDictReferService;
    @Autowired
    LabItemDictCriticalMapper criticalMapper;
    @Autowired
    LabItemDictCriticalService criticalService;
    @Autowired
    LabChannelService channelService;

    @Override
    public Result findLabItemDictList(LabItemDict labLabItemDict) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);


        if (StringUtils.isNotBlank(labLabItemDict.getOrgId())) {
            lambdaQueryWrapper.eq(LabItemDict::getOrgId, labLabItemDict.getOrgId());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getItemClass())) {
            lambdaQueryWrapper.eq(LabItemDict::getItemClass, labLabItemDict.getItemClass());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getInstrClass())) {
            lambdaQueryWrapper.eq(LabItemDict::getInstrClass, labLabItemDict.getInstrClass());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getRptGroup())) {
            lambdaQueryWrapper.eq(LabItemDict::getRptGroup, labLabItemDict.getRptGroup());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getIsTran())) {
            lambdaQueryWrapper.eq(LabItemDict::getIsTran, labLabItemDict.getIsTran());
        }
        if (Objects.nonNull(labLabItemDict.getPoct())) {
            lambdaQueryWrapper.eq(LabItemDict::getPoct, labLabItemDict.getPoct());
        }

        if (StringUtils.isNotBlank(labLabItemDict.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNo, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemNa, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnName, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnCode, labLabItemDict.getSearchValue()).or().like(LabItemDict::getInputCode, labLabItemDict.getSearchValue()));
        }
        if (labLabItemDict.getEnable() != null) {
            lambdaQueryWrapper.eq(LabItemDict::getEnable, labLabItemDict.getEnable());
        }
        lambdaQueryWrapper.selectAll(LabItemDict.class);
        lambdaQueryWrapper.selectAs("a", LabFeeItem::getFeeName, LabItemDict::getErFeeitemName).leftJoin(LabFeeItem.class, "a", p -> p.eq(LabFeeItem::getFeeCode, LabItemDict::getErFeeitemCode).eq(LabFeeItem::getDelFlag, 0));
        lambdaQueryWrapper.selectAs("b", LabFeeItem::getFeeName, LabItemDict::getMapperItemName).leftJoin(LabFeeItem.class, "b", p -> p.eq(LabFeeItem::getFeeCode, LabItemDict::getMapperItemCode).eq(LabFeeItem::getDelFlag, 0));
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabItemDict::getRptGroupName);
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", p -> p.eq(LabRptGroup::getRptGroup, LabItemDict::getRptGroup).eq(LabRptGroup::getDelFlag, 0));

        lambdaQueryWrapper.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        List<LabItemDict> collect1 = labItemDicts.stream().sorted(Comparator.comparing(LabItemDict::getSeq, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());

        return Result.succ(1, "查询成功！", collect1);
    }

    @Override
    public Result findLabItemDictManualList(LabItemDict labLabItemDict) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(labLabItemDict.getOrgId())) {
            lambdaQueryWrapper.eq(LabItemDict::getOrgId, labLabItemDict.getOrgId());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getRptGroup())) {
            lambdaQueryWrapper.eq(LabItemDict::getRptGroup, labLabItemDict.getRptGroup());
        }

        if (StringUtils.isNotBlank(labLabItemDict.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNo, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemNa, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnName, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnCode, labLabItemDict.getSearchValue()).or().like(LabItemDict::getInputCode, labLabItemDict.getSearchValue()));
        }
        if (labLabItemDict.getEnable() != null) {
            lambdaQueryWrapper.eq(LabItemDict::getEnable, labLabItemDict.getEnable());
        }
        lambdaQueryWrapper.selectAll(LabItemDict.class);
        lambdaQueryWrapper.selectAs("a", LabFeeItem::getFeeName, LabItemDict::getErFeeitemName).leftJoin(LabFeeItem.class, "a", LabFeeItem::getFeeCode, LabItemDict::getErFeeitemCode);
        lambdaQueryWrapper.selectAs("b", LabFeeItem::getFeeName, LabItemDict::getMapperItemName).leftJoin(LabFeeItem.class, "b", LabFeeItem::getFeeCode, LabItemDict::getMapperItemCode);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabItemDict::getRptGroupName);
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabItemDict::getRptGroup);

        lambdaQueryWrapper.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        List<LabItemDict> collect1 = labItemDicts.stream().sorted(Comparator.comparing(LabItemDict::getSeq, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        List<Map<String, Object>> labFeeItemsAsMaps = collect1.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());

            map.put("rptGroup", item.getRptGroup());
            map.put("itemNo", item.getItemNo());
            map.put("itemNa", item.getItemNa());
            return map;
        }).collect(Collectors.toList());
        LambdaQueryWrapper<QiIndexFeeitemManual> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QiIndexFeeitemManual::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotBlank(labLabItemDict.getRptGroup()), QiIndexFeeitemManual::getRptGroup, labLabItemDict.getRptGroup());
        List<QiIndexFeeitemManual> qiIndexFeeitemManuals = qiIndexFeeitemManualMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(qiIndexFeeitemManuals)) {
            for (Map<String, Object> labFeeItemsAsMap : labFeeItemsAsMaps) {
                qiIndexFeeitemManuals.stream().filter(a -> a.getFeeCode().equals(labFeeItemsAsMap.get("itemNo")) && a.getRptGroup().equals(labFeeItemsAsMap.get("rptGroup"))).findFirst().ifPresent(stringObjectMap -> labFeeItemsAsMap.put("isManual", "1"));
            }
        }
        return Result.succ(1, "查询成功！", labFeeItemsAsMaps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addLabItemDict(LabItemDict labItemDictParam) {
        //项目判断：项目代号，不能有重复的，若此报告单元里面有这个项目代号时，要弹框提示，不能保存上。
        //itemCode rptGroupId
        //根据报告单元id和itemcode查看是否存在数据
        LambdaQueryWrapper<LabItemDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabItemDict::getItemNo, labItemDictParam.getItemNo()).eq(LabItemDict::getRptGroup, labItemDictParam.getRptGroup()).eq(LabItemDict::getDelFlag, 0);
        int count = this.count(queryWrapper);
        if (count > 0) {
            return Result.fail("此项目代号已存在，添加失败！");
        }
        LabItemDict labItemDict = new LabItemDict();
        BeanUtil.copyProperties(labItemDictParam, labItemDict);
        boolean save = this.save(labItemDict);
        if (save) {
            //默认插入一条通道号
            LambdaQueryWrapper<LabInstrSetup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabInstrSetup::getRptGroup, labItemDict.getRptGroup()).eq(LabInstrSetup::getDelFlag, 0);
            List<LabInstrSetup> labInstrSetups = labInstrSetupMapper.selectList(lambdaQueryWrapper);

            if (CollectionUtils.isNotEmpty(labInstrSetups)) {
                LabChannel labChannel = new LabChannel();
                labChannel.setChannelCode(labItemDict.getItemNo());
                labChannel.setRptGroup(labItemDict.getRptGroup());
                labChannel.setItemNo(labItemDict.getItemNo());
                labChannel.setItemDictName(labItemDict.getItemNa());
                labChannel.setInstrCode(labInstrSetups.get(0).getInstrCode());
                labChannelMapper.insert(labChannel);
            }
            return Result.succ(1, "添加成功！", labItemDict);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result editLabItemDict(LabItemDict labItemDictParam) {
        //项目判断：项目代号，不能有重复的，若此报告单元里面有这个项目代号时，要弹框提示，不能保存上。
        //itemCode rptGroupId
        //根据报告单元id和itemcode查看是否存在数据
        LambdaQueryWrapper<LabItemDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabItemDict::getItemNo, labItemDictParam.getItemNo()).eq(LabItemDict::getRptGroup, labItemDictParam.getRptGroup()).ne(LabItemDict::getId, labItemDictParam.getId()).eq(LabItemDict::getDelFlag, 0);
        int count = this.count(queryWrapper);
        if (count > 0) {
            return Result.fail("此项目代号已存在，修改失败！", labItemDictParam);
        }
        LabItemDict labItemDict = new LabItemDict();
        BeanUtil.copyProperties(labItemDictParam, labItemDict);
        boolean b = this.updateById(labItemDict);
        if (b) {
            return Result.succ(1, "编辑成功！", labItemDict);
        } else {
            return Result.fail("编辑失败！", labItemDict);
        }
    }

    @Autowired
    LabFeeitemVsItemDictMapper labFeeitemVsItemDictMapper;
    @Override
    public Result deleteLabItemDict(LabItemDict labItemDictParam) {
        LabItemDict labItemDict = new LabItemDict();
        BeanUtil.copyProperties(labItemDictParam, labItemDict);
        labItemDict.setDelFlag(1);
        boolean b = this.updateById(labItemDict);
        if (b) {
            //同时删除项目与申请项目对照表的数据
            String rptGroup = labItemDictParam.getRptGroup();
            String itemNo = labItemDictParam.getItemNo();
            //根据rptGroup，itemNo 删除LAB_FEEITEM_VS_ITEMDICT表
            LambdaQueryWrapper<LabFeeitemVsItemDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabFeeitemVsItemDict::getRptGroup, rptGroup).eq(LabFeeitemVsItemDict::getItemNo, itemNo).eq(LabFeeitemVsItemDict::getOrgId,labItemDictParam.getOrgId());
            labFeeitemVsItemDictMapper.delete(lambdaQueryWrapper);

            return Result.succ(1, "删除成功！", null);
        } else {
            return Result.fail("删除失败！");
        }
    }

    @Override
    public Result findLabItemDict(LabItemDict labItemDictParam) {
        return Result.succ(1, "查询成功！", labReportItemMapper.selectById(labItemDictParam.getId()));
    }

    @Override
    public Result findLabItemPageList(CommonPageDto pageParam) {
        Page<LabItemDict> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<LabItemDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNa, pageParam.getSeachValue()).or().like(LabItemDict::getItemNo, pageParam.getSeachValue()));
        }
        if (StringUtils.isNotBlank(pageParam.getCode())) {
            lambdaQueryWrapper.eq(LabItemDict::getItemClass, pageParam.getCode());
        }
        lambdaQueryWrapper.orderByAsc(LabItemDict::getSeq);
        Page<LabItemDict> rulePage = labReportItemMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", rulePage);
    }

    @Override
    public Result findLabItemPageList1(CommonPageDto pageParam) {
        Page<LabItemDict> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<LabItemDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNa, pageParam.getSeachValue()).or().like(LabItemDict::getItemNo, pageParam.getSeachValue()));
        }
        if (StringUtils.isNotBlank(pageParam.getCode())) {
            lambdaQueryWrapper.eq(LabItemDict::getItemClass, pageParam.getCode());
        }
        lambdaQueryWrapper.isNotNull(LabItemDict::getRptGroup);
        lambdaQueryWrapper.orderByAsc(LabItemDict::getSeq);
        Page<LabItemDict> rulePage = labReportItemMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", rulePage);
    }

    @Override
    public Result findJoinLabItemDictList(LabItemDict labLabItemDict) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.selectAll(LabItemDict.class);
        lambdaQueryWrapper.selectAs("rg", LabRptGroup::getRptGroupName, LabItemDict::getRptGroupName);
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rg", LabRptGroup::getRptGroup, LabItemDict::getRptGroup);
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        if (StringUtils.isNotBlank(labLabItemDict.getOrgId())) {
            lambdaQueryWrapper.eq(LabItemDict::getOrgId, labLabItemDict.getOrgId());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getItemClass())) {
            lambdaQueryWrapper.eq(LabItemDict::getItemClass, labLabItemDict.getItemClass());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getInstrClass())) {
            lambdaQueryWrapper.eq(LabItemDict::getInstrClass, labLabItemDict.getInstrClass());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getRptGroup())) {
            lambdaQueryWrapper.eq(LabItemDict::getRptGroup, labLabItemDict.getRptGroup());
        }
        if (StringUtils.isNotBlank(labLabItemDict.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabItemDict::getItemNo, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemNa, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnName, labLabItemDict.getSearchValue()).or().like(LabItemDict::getItemEnCode, labLabItemDict.getSearchValue()).or().like(LabItemDict::getInputCode, labLabItemDict.getSearchValue()));
        }
        if (labLabItemDict.getEnable() != null) {
            lambdaQueryWrapper.eq(LabItemDict::getEnable, labLabItemDict.getEnable());
        }
        lambdaQueryWrapper.orderByAsc(LabItemDict::getSeq);
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", labItemDicts);
    }

    @Override
    public Result findLabItemDictListByInstr(QcInstrSampleParam param) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabItemDict.class)
                .leftJoin(LabInstrSetup.class, "lis", LabInstrSetup::getRptGroup, LabItemDict::getRptGroup)
                .eq(LabItemDict::getDelFlag, 0)
                .eq(LabInstrSetup::getId, param.getInstrId());
        if(ToolsUtils.isNotEmpty(param.getPoct())){
            lambdaQueryWrapper.eq(LabItemDict::getPoct, param.getPoct());
        }
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", labItemDicts);
    }

    @Override
    public Result findLabItemDictAndAllListByInstr(QcInstrSampleParam param) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabItemDict.class)
                .leftJoin(LabInstrSetup.class, "lis", LabInstrSetup::getRptGroup, LabItemDict::getRptGroup)
                .eq(LabItemDict::getDelFlag, 0)
                .eq(LabInstrSetup::getId, param.getInstrId());
        if(ToolsUtils.isNotEmpty(param.getPoct())){
            lambdaQueryWrapper.eq(LabItemDict::getPoct, param.getPoct());
        }
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        List<LabItemDict> returnList = new ArrayList<>();
        LabItemDict allDict = new LabItemDict();
        allDict.setId("all");
        allDict.setItemNa("所有项目");
        allDict.setItemEnCode("all");
        allDict.setInputCode("all");
        allDict.setItemNo("all");
        returnList.add(allDict);
        returnList.addAll(labItemDicts);
        return Result.succ(1, "查询成功！", returnList);
    }

    @Override
    public Result syncItemDicts() {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    LabItemDict labItemDict = new LabItemDict();
                    labItemDict.setOrgId(orgId);
                    String returnMsg1 = HttpUtil.createPost(webUrl + "/public/syncItemDict").body(JSONUtil.toJsonStr(labItemDict)).contentType("application/json").execute().body();
                    JSONObject reportObject = new JSONObject(returnMsg1);
                    JSONObject reportStatus = reportObject.getJSONObject("status");
                    String reportCode = reportStatus.get("code").toString();
                    if ("400".equals(reportCode)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }


        return Result.succ(1, "请求成功", null);
    }

    @Override
    public Result updateMoveItemDictSeq(LabItemDictDto dto) {
        List<LabItemDict> labItemDictList = dto.getLabItemDictList();
        boolean b = this.saveOrUpdateBatch(labItemDictList);
        if (b) {
            return Result.succ(1, "修改成功", null);
        } else {
            return Result.fail(400, "修改失败", "");
        }

    }

    /*知识库获取所有项目*/
    @Override
    public Result findAllItemDictList(LabItemDict labItemDict) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.select(LabItemDict::getItemNo, LabItemDict::getItemNa);
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        lambdaQueryWrapper.isNotNull(LabItemDict::getItemNo);
        lambdaQueryWrapper.isNotNull(LabItemDict::getItemNa);
        lambdaQueryWrapper.ne(LabItemDict::getItemNo, "");
        lambdaQueryWrapper.ne(LabItemDict::getItemNa, "");
        if (StringUtils.isNotBlank(labItemDict.getSearchValue())) {
            lambdaQueryWrapper.and(p -> p.like(LabItemDict::getItemNo, labItemDict.getSearchValue()).or().like(LabItemDict::getItemNa, labItemDict.getSearchValue()));
        }

        if (BeanUtil.isNotEmpty(labItemDict.getEnable())) {
            lambdaQueryWrapper.eq(LabItemDict::getEnable, labItemDict.getEnable());
        }

        lambdaQueryWrapper.groupBy(LabItemDict::getItemNo, LabItemDict::getItemNa);
        List<LabItemDict> itemList = labReportItemMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "成功", itemList);
    }

    /*获取项目知识库*/
    @Override
    public Result findItemDictKnoInfo(FindItemDictKnoInfoParam input) {
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        lambdaQueryWrapper.eq(LabItemDict::getItemNo, input.getItemNo());
        if (StringUtils.isNotBlank(input.getItemNa())) {
            lambdaQueryWrapper.eq(LabItemDict::getItemNa, input.getItemNa());
        }

        List<LabItemDict> itemList = labReportItemMapper.selectList(lambdaQueryWrapper);
        if (itemList.isEmpty()) {
            return Result.fail("查无项目");
        }

        LabItemDict itemEntry = itemList.get(0);

        ExtenFieldsValuePageRequestDto param = new ExtenFieldsValuePageRequestDto();
        param.setModuleId(input.getModuleId());
        param.setMenuId(input.getMenuId());
        param.setTabKey(input.getTabKey());
        param.setBusRowId(itemEntry.getId());
        return sysExtenFieldsValueService.findExtenFieldsValueList(param);//findExtenFieldsValueList
    }

    @Override
    public Result batchSaveDictItem(StaDictItemSyncDto itemSyncDto) {
        List<StaItemDict> staItemDicts = itemSyncDto.getStaItemDicts();
        //staItemDicts集合根据itemNo 进行过滤
        List<StaItemDict> filteredList = staItemDicts.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                StaItemDict::getItemNo,
                                item -> item,
                                (existing, replacement) -> existing // 保留第一个出现的 itemNo
                        ),
                        map -> new ArrayList<>(map.values())
                ));

        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(new LambdaQueryWrapper<LabItemDict>().eq(LabItemDict::getDelFlag, 0).eq(LabItemDict::getRptGroup, itemSyncDto.getRptGroup()));

        // 将 labItemDicts 中的 itemNo 收集到一个 Set 中，以便快速查找
        Set<String> labItemNoSet = labItemDicts.stream()
                .map(LabItemDict::getItemNo)
                .collect(Collectors.toSet());

        // 过滤 filteredList 中不在 labItemNoSet 中的元素
        List<StaItemDict> collect = filteredList.stream().filter(staItemDict -> !labItemNoSet.contains(staItemDict.getItemNo())).collect(Collectors.toList());
        List<LabItemDict> list = new ArrayList<>();
        for (StaItemDict staItemDict : collect) {
            LabItemDict labItemDict = new LabItemDict();
            BeanUtil.copyProperties(staItemDict, labItemDict,"id");
            labItemDict.setRptGroup(itemSyncDto.getRptGroup());
            labItemDict.setEnable(1);
            list.add(labItemDict);
        }
        this.saveBatch(list);
        return Result.succ(1,"成功","");
    }

    @Override
    public void export(String rptGroup, HttpServletResponse response) {
        //检验项目
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.eq(LabItemDict::getDelFlag, 0);
        lambdaQueryWrapper.eq(LabItemDict::getRptGroup, rptGroup);
        List<LabItemDict> labItemDicts = labReportItemMapper.selectList(lambdaQueryWrapper);
        List<LabItemDictCopy>copies1=new ArrayList<>();
        for (LabItemDict labItemDict : labItemDicts) {
            LabItemDictCopy labItemDictCopy = new LabItemDictCopy();
            BeanUtil.copyProperties(labItemDict, labItemDictCopy);
            copies1.add(labItemDictCopy);
        }
        //参考范围
        MPJLambdaWrapper<LabItemDictRefer> itemDictReferWrpper = new MPJLambdaWrapper<>();
        itemDictReferWrpper
                .eq(LabItemDictRefer::getRptGroup, rptGroup)
                .eq(LabItemDictRefer::getDelFlag, 0);
        List<LabItemDictRefer> itemDictReferList = itemDictReferMapper.selectList(itemDictReferWrpper);
        List<LabItemDictReferCopy> itemCopyList=new ArrayList<>();
        for (LabItemDictRefer labItemDictRefer : itemDictReferList) {
            LabItemDictReferCopy labItemDictCopy = new LabItemDictReferCopy();
            BeanUtil.copyProperties(labItemDictRefer, labItemDictCopy);
            itemCopyList.add(labItemDictCopy);
        }
        //危急值
        MPJLambdaWrapper<LabItemDictCritical> dictCriticalWrapper = new MPJLambdaWrapper<>();
        dictCriticalWrapper
                .eq(LabItemDictCritical::getRptGroup, rptGroup)
                .eq(LabItemDictCritical::getDelFlag, 0);
        List<LabItemDictCritical> dictCriticalList = criticalMapper.selectList(dictCriticalWrapper);
        List<LabItemDictCriticalCopy>dictCriticalCopies=new ArrayList<>();
        for (LabItemDictCritical labItemDictCritical : dictCriticalList) {
            LabItemDictCriticalCopy labItemDictCopy = new LabItemDictCriticalCopy();
            BeanUtil.copyProperties(labItemDictCritical, labItemDictCopy);
            dictCriticalCopies.add(labItemDictCopy);
        }
        //通道号
        MPJLambdaWrapper<LabChannel> labChannelMPJLambdaWrapper = new MPJLambdaWrapper();
        labChannelMPJLambdaWrapper.eq(LabChannel::getRptGroup, rptGroup);
        labChannelMPJLambdaWrapper.eq(LabChannel::getDelFlag, 0);
        List<LabChannel> channelList = labChannelMapper.selectList(labChannelMPJLambdaWrapper);
        List<LabChannelCopy>channelCopyList=new ArrayList<>();
        for (LabChannel labChannel : channelList) {
            LabChannelCopy labChannelCopy = new LabChannelCopy();
            BeanUtil.copyProperties(labChannel, labChannelCopy);
            channelCopyList.add(labChannelCopy);
        }

        // 3、组装excel数据
        List<EasyExcelSheet> excelSheets ;
        EasyExcelSheet<LabItemDictCopy> jianyanSheet = EasyExcelSheet.<LabItemDictCopy>builder()
                .sheetIndex(0)
                .sheetName("检验项目")
                .headClass(LabItemDictCopy.class)
                .dataset(copies1)
                .build();
        EasyExcelSheet<LabItemDictReferCopy> ckfwSheet = EasyExcelSheet.<LabItemDictReferCopy>builder()
                .sheetIndex(1)
                .sheetName("参考范围")
                .headClass(LabItemDictReferCopy.class)
                .dataset(itemCopyList)
                .build();
        EasyExcelSheet<LabItemDictCriticalCopy> wjzSheet = EasyExcelSheet.<LabItemDictCriticalCopy>builder()
                .sheetIndex(2)
                .sheetName("危急值")
                .headClass(LabItemDictCriticalCopy.class)
                .dataset(dictCriticalCopies)
                .build();
        EasyExcelSheet<LabChannelCopy> tongdaohaoSheet = EasyExcelSheet.<LabChannelCopy>builder()
                .sheetIndex(3)
                .sheetName("通道号")
                .headClass(LabChannelCopy.class)
                .dataset(channelCopyList)
                .build();


        excelSheets = Arrays.asList(jianyanSheet,ckfwSheet,wjzSheet,tongdaohaoSheet);
        EasyExcelExport.downloadMultipleSheetExcel(rptGroup, response, excelSheets);
    }

    @Override
    public Result uploadDetailByExcel(MultipartFile file, HttpServletRequest request) throws IOException {
        String rptGroup = request.getParameter("rptGroup");

        // 将 MultipartFile 写入临时文件
        File tempFile = File.createTempFile("upload-", ".xlsx");
        file.transferTo(tempFile);
        EasyExcel.read(tempFile, LabItemDictCopy.class, new PageReadListener<LabItemDictCopy>(dataList -> {
            for (LabItemDictCopy labItemDictCopy : dataList) {
                labItemDictCopy.setRptGroup(rptGroup);
                LabItemDict labItemDict = new LabItemDict();
                BeanUtil.copyProperties(labItemDictCopy, labItemDict);
                this.saveOrUpdate(labItemDict,new LambdaQueryWrapper<LabItemDict>().eq(LabItemDict::getItemNo,labItemDict.getItemNo()).eq(LabItemDict::getRptGroup,labItemDict.getRptGroup()).eq(LabItemDict::getDelFlag,0));
            }

        })).sheet("检验项目").doRead();

        EasyExcel.read(tempFile, LabItemDictReferCopy.class, new PageReadListener<LabItemDictReferCopy>(dataList -> {
            List<LabItemDictRefer>itemDictReferList=new ArrayList<>();
            for (LabItemDictReferCopy labItemDictReferCopy : dataList) {
                labItemDictReferCopy.setRptGroup(rptGroup);
                LabItemDictRefer labItemDictRefer = new LabItemDictRefer();
                BeanUtil.copyProperties(labItemDictReferCopy, labItemDictRefer);
                itemDictReferList.add(labItemDictRefer);
            }
            itemDictReferService.saveBatch(itemDictReferList);
        })).sheet("参考范围").doRead();

        EasyExcel.read(tempFile, LabItemDictCriticalCopy.class, new PageReadListener<LabItemDictCriticalCopy>(dataList -> {
            List<LabItemDictCritical>dictCriticalList=new ArrayList<>();
            for (LabItemDictCriticalCopy labItemDictCriticalCopy : dataList) {
                labItemDictCriticalCopy.setRptGroup(rptGroup);
                LabItemDictCritical labItemDictCritical = new LabItemDictCritical();
                BeanUtil.copyProperties(labItemDictCriticalCopy, labItemDictCritical);
                dictCriticalList.add(labItemDictCritical);
            }
            criticalService.saveBatch(dictCriticalList);
        })).sheet("危急值").doRead();

        EasyExcel.read(tempFile, LabChannelCopy.class, new PageReadListener<LabChannelCopy>(dataList -> {
            for (LabChannelCopy labChannelCopy : dataList) {
                labChannelCopy.setRptGroup(rptGroup);
                LabChannel labChannel = new LabChannel();
                BeanUtil.copyProperties(labChannelCopy, labChannel);
                channelService.saveOrUpdate(labChannel,new LambdaQueryWrapper<LabChannel>().eq(LabChannel::getItemNo,labChannel.getItemNo()).eq(LabChannel::getRptGroup,labChannel.getRptGroup()).eq(LabChannel::getInstrCode,labChannel.getInstrCode()).eq(LabChannel::getChannelCode,labChannel.getChannelCode()).eq(LabChannel::getDelFlag,0));
            }
        })).sheet("通道号").doRead();
        return Result.succ("上传成功");
    }

    @Override
    public Result uploadBaseTemplate(MultipartFile file, HttpServletRequest request) throws IOException {

        List<LabItemDict> itemDicts = this.list(new LambdaQueryWrapper<LabItemDict>().eq(LabItemDict::getDelFlag, 0));
        Map<String, List<LabItemDict>> itemDictMap = itemDicts.stream().filter(p -> StringUtils.isNotBlank(p.getItemNo())).collect(Collectors.groupingBy(LabItemDict::getItemNo));

        // 将 MultipartFile 写入临时文件
        File tempFile = File.createTempFile("upload-", ".xlsx");
        file.transferTo(tempFile);
        EasyExcel.read(tempFile, KnowBase.class, new PageReadListener<KnowBase>(dataList -> {
            for (KnowBase knowBase : dataList) {
                if (StringUtils.isNotBlank(knowBase.getItemNo())){
                    List<LabItemDict> itemDicts1 = itemDictMap.get(knowBase.getItemNo());
                    if (CollectionUtils.isNotEmpty(itemDicts1)){
                        for (LabItemDict labItemDict : itemDicts1) {
                            SysExtenFieldsValue analyFieldsValue = new SysExtenFieldsValue();
                            analyFieldsValue.setFieldId("1787668556831473666");
                            analyFieldsValue.setFieldName("分析原理");
                            analyFieldsValue.setFieldCode("analysisPrinciple");
                            analyFieldsValue.setBusRowId(labItemDict.getId());
                            analyFieldsValue.setDataType("Strng");
                            analyFieldsValue.setValue(knowBase.getAnalysisPrinciple());
                            sysExtenFieldsValueService.saveOrUpdate(analyFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556831473666").eq(SysExtenFieldsValue::getDelFlag, 0));

                            SysExtenFieldsValue operFieldsValue = new SysExtenFieldsValue();
                            operFieldsValue.setFieldId("1787668556865028098");
                            operFieldsValue.setFieldName("操作说明");
                            operFieldsValue.setFieldCode("operationInstruction");
                            operFieldsValue.setBusRowId(labItemDict.getId());
                            operFieldsValue.setDataType("Strng");
                            operFieldsValue.setValue(knowBase.getOperationInstruction());
                            sysExtenFieldsValueService.saveOrUpdate(operFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556865028098").eq(SysExtenFieldsValue::getDelFlag, 0));

                            SysExtenFieldsValue clinFieldsValue = new SysExtenFieldsValue();
                            clinFieldsValue.setFieldId("1787668556890193921");
                            clinFieldsValue.setFieldName("临床意义");
                            clinFieldsValue.setFieldCode("clinicalSignificance");
                            clinFieldsValue.setBusRowId(labItemDict.getId());
                            clinFieldsValue.setDataType("Strng");
                            clinFieldsValue.setValue(knowBase.getClinicalSignificance());
                            sysExtenFieldsValueService.saveOrUpdate(clinFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556890193921").eq(SysExtenFieldsValue::getDelFlag, 0));


                            SysExtenFieldsValue consFieldsValue = new SysExtenFieldsValue();
                            consFieldsValue.setFieldId("1787668556927942657");
                            consFieldsValue.setFieldName("注意事项");
                            consFieldsValue.setFieldCode("considerations");
                            consFieldsValue.setBusRowId(labItemDict.getId());
                            consFieldsValue.setDataType("Strng");
                            consFieldsValue.setValue(knowBase.getConsiderations());
                            sysExtenFieldsValueService.saveOrUpdate(consFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556927942657").eq(SysExtenFieldsValue::getDelFlag, 0));



                            SysExtenFieldsValue perforFieldsValue = new SysExtenFieldsValue();
                            perforFieldsValue.setFieldId("1787668556961497090");
                            perforFieldsValue.setFieldName("性能特征");
                            perforFieldsValue.setFieldCode("performanceCharacteristics");
                            perforFieldsValue.setBusRowId(labItemDict.getId());
                            perforFieldsValue.setDataType("Strng");
                            perforFieldsValue.setValue(knowBase.getPerformanceCharacteristics());
                            sysExtenFieldsValueService.saveOrUpdate(perforFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556961497090").eq(SysExtenFieldsValue::getDelFlag, 0));

                            SysExtenFieldsValue refFieldsValue = new SysExtenFieldsValue();
                            refFieldsValue.setFieldId("1787668556995051521");
                            refFieldsValue.setFieldName("参考文献");
                            refFieldsValue.setFieldCode("references");
                            refFieldsValue.setBusRowId(labItemDict.getId());
                            refFieldsValue.setDataType("Strng");
                            refFieldsValue.setValue(knowBase.getReferences());
                            sysExtenFieldsValueService.saveOrUpdate(refFieldsValue,new LambdaQueryWrapper<SysExtenFieldsValue>().eq(SysExtenFieldsValue::getBusRowId, labItemDict.getId()).eq(SysExtenFieldsValue::getFieldId, "1787668556995051521").eq(SysExtenFieldsValue::getDelFlag, 0));

                        }
                    }
                }
            }

        })).sheet("sheet").doRead();
        return Result.succ("上传成功");
    }
}
